/**
 * 
 */
package com.flashdeck.domain;

import java.util.ArrayList;

import org.apache.commons.lang.StringUtils;
import org.xml.sax.AttributeList;
import org.xml.sax.HandlerBase;
import org.xml.sax.SAXException;

/**
 * @author Vincentas
 *
 */
public class DeckHandler extends HandlerBase {

	private StringBuilder stringBuilder = new StringBuilder();
	
	private Deck deck;
	
	private DeckInfo deckInfo;
	
	private Card card;
	
	/* (non-Javadoc)
	 * @see org.xml.sax.HandlerBase#characters(char[], int, int)
	 */
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		super.characters(ch, start, length);
		stringBuilder.append(ch, start, length);
	}
	
	private String getText() {
		String result = StringUtils.strip(stringBuilder.toString());
		stringBuilder.setLength(0);
		return result;
	}

	/* (non-Javadoc)
	 * @see org.xml.sax.HandlerBase#endElement(java.lang.String)
	 */
	@Override
	public void endElement(String name) throws SAXException {		
		super.endElement(name);
		
		if (name.equalsIgnoreCase("name")) {
			deckInfo.setName(getText());
		} else if (name.equalsIgnoreCase("description")) {
			deckInfo.setDescription(getText());
		} else if (name.equalsIgnoreCase("front")) {
			card.setFront(getText());
		} else if (name.equalsIgnoreCase("back")) {
			card.setBack(getText());
		} else if (name.equalsIgnoreCase("card")) {
			deck.getCards().add(card);
		}		
	}
	
	/* (non-Javadoc)
	 * @see org.xml.sax.HandlerBase#startDocument()
	 */
	@Override
	public void startDocument() throws SAXException {
		super.startDocument();
		
		deckInfo = new DeckInfo();
		deck = new Deck();	
		deck.setCards(new ArrayList<Card>());	
		deck.setDeckInfo(deckInfo);
	}

	/* (non-Javadoc)
	 * @see org.xml.sax.HandlerBase#startElement(java.lang.String, org.xml.sax.AttributeList)
	 */
	@Override
	public void startElement(String name, AttributeList attributes)	throws SAXException {
		super.startElement(name, attributes);
		
		if (name.equalsIgnoreCase("card")) {
			card = new Card();
		}
	}
	
	public Deck getDeck() {
		return deck;
	}	
	
	public DeckInfo getDeckInfo() {
		return deckInfo;
	}
}
